﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Marmat.Common.Http
{

    /// <summary>
    /// Json序列化支持。
    /// </summary>
    public class JsonResultFilterAttribute : ResultFilterAttribute
    {
        /// <summary>
        /// 返回结果前执行。
        /// </summary>
        /// <param name="context"></param>
        public override void OnResultExecuting(ApiActionContext context)
        {
            if (context.ReturnValue is null)
            {
                string resultString = this.ReadAsString(context);
                context.ReturnValue = Newtonsoft.Json.JsonConvert.DeserializeObject(resultString, context.ActionDescriptor.ReturnType);
            }
        }

        /// <summary>
        /// 将 HTTP 内容序列化到字符串。
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string ReadAsString(ApiActionContext context)
        {
            string resultString;
            Encoding encoding = new UTF8Encoding();
            using (System.IO.Stream resStream = context.Response.GetResponseStream())
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(resStream, encoding);
                resultString = reader.ReadToEnd();
                reader.Close();
                resStream.Close();
            }
            return resultString;
        }
    }
}
